<template>
  <div>

  </div>
</template>

<script setup>
import * as Cesium from "cesium";
import { onUnmounted } from "vue";
import GridCell from "./GridCell_v2";
import UavModelLayerClass from "./UavModelLayerClass.js";

// 无人机相关变量
let uavModelLayer = null;
const uavLayerMap = new Map();
let flightInterval = null;
let currentIndex = 0;
let trajectoryData = [];

async function initialize (viewer) {
  // const data = await getPlaneGridData();
  // const gridData = JSON.parse(data.data.airRouteGeom);
  // console.log(gridData, "initialize");

  // 初始化无人机图层
  uavModelLayer = new UavModelLayerClass(viewer, uavLayerMap);

  // 获取公共数据
  const publicData = await getGridDataPublic('json5', '15855375A8A3OM6H1912-test.json');
  const publicDataEvent = JSON.stringify({
    type: 'LineString',
    coordinates: publicData
  });

  // 调用均匀分布接口
  const distributionData = await getEvenDistribution({
    distance: 5,
    // lineGeom: data.data.airRouteGeom
    lineGeom: publicDataEvent
  });
  console.log(distributionData, "distributionData");

  const distributionDataEvent = JSON.parse(distributionData.data.geomLine).coordinates;


  viewer.camera.flyTo({
    destination: Cesium.Cartesian3.fromDegrees(
      publicData[0][0],
      publicData[0][1],
      1000
    ),
    duration: 2,
  });

  const gridCell = new GridCell(viewer, publicData[0]);
  const gridCellPlan = new GridCell(viewer, publicData[0]);
  gridCellPlan.loadGridDataJson(distributionDataEvent, 'Green');



  const firstPosition = distributionDataEvent[0];
  const uavConfig = {
    snCode: "UAV-FLIGHT-001",
    initPostion: firstPosition,
    ownerType: 1, // 企业类型
    productCode: "沿轨迹飞行无人机",
    speedNum: 15,
    height: firstPosition[2],
    img: "/img/uav_2_1.svg",
    flightStatus: false
  };
  uavModelLayer.addUav(uavConfig);


  let currentIndex = 0;
  // 创建无人机并开始飞行
  setInterval(() => {

    if (currentIndex >= distributionDataEvent.length) {
      currentIndex = 0;
    }

    const position = distributionDataEvent[currentIndex];
    console.log(position, "position");

    moveUav(position);

    // gridCell.changeColor({
    //   position: position,
    //   color: 'White',
    //   isGridColor: true,
    //   mode: 1,
    // });

    gridCellPlan.changeColor({
      position: position,
      color: 'White',
      isGridColor: true,
      mode: 1,
    });

    // gridCell.drawSingleBox(position, 'Red');
    // viewer.entities.add({
    //   position: Cesium.Cartesian3.fromDegrees(position[0], position[1], position[2]),
    //   point: {
    //     color: Cesium.Color.BLUE,
    //     pixelSize: 10
    //   }
    // });

    // 更新网格
    currentIndex++
  }, 2000);
}

/**
 * 无人机飞行
 * @param position 
 */
function moveUav (position) {

  const uavObj = {
    snCode: "UAV-FLIGHT-001",
    position: position
  };

  // 调用无人机图层的移动方法
  uavModelLayer.moveUav(uavObj);
}

async function getPlaneGridData () {
  // 发送指定的id参数到接口
  const response = await fetch('https://www.servicetrial.com/xq/cq/uav/api-plan/plan/infoPlan', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer d1c049bd-fd30-4bc7-99fc-34299bca5355'
    },
    body: JSON.stringify({
      id: "b102bd00-36f2-11f0-ab76-92a5fc17e8d9"
    })
  });
  const data = await response.json();
  return data;
}

async function getEvenDistribution (params) {
  try {
    const response = await fetch('https://www.servicetrial.com/xq/cq/uav/api-uav-simulation/uav/simulation/evenDistribution', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer 2250c1e1-b88a-48ab-9134-2d316924b2e4'
      },
      body: JSON.stringify({
        ...params
      })
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const data = await response.json();
    return data;
  } catch (error) {
    console.error('获取均匀分布数据失败:', error);
    return null;
  }
}


async function getGridDataPublic (path, filename) {
  try {
    const response = await fetch(`/${path}/${filename}`);

    if (!response.ok) {
      throw new Error(`无法加载文件: ${filename}, 状态码: ${response.status}`);
    }

    const data = await response.json();
    return data;
  } catch (error) {
    console.error('获取JSON数据失败:', error);
    return null;
  }
}

defineExpose({
  initialize,
})

</script>

<style lang="scss" scoped></style>